package com.hefan.api.controller.dynamic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cat.common.entity.Page;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.hefan.api.service.TripInfoLocalService;
import com.hefan.club.dynamic.bean.TripInfo;
import com.hefan.common.util.HttpUtils;
import com.hefan.common.util.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/v1/personalTrip")
public class TripController {

	public static Logger logger = LoggerFactory.getLogger(TripController.class);

	@Resource
	TripInfoLocalService tripInfoLocalService;

	/**
	 * 获取行程类型列表
	 * 
	 * @Title: findTripsTypeInfoList
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param request
	 * @return
	 * @return: String
	 * @author: LiTeng
	 * @throws @date:
	 *             2016年10月17日 上午9:45:57
	 */
	@RequestMapping("/findTripsTypeInfoList")
	@ResponseBody
	public String findTripsTypeInfoList(HttpServletRequest request) {
		ResultBean res = new ResultBean();
		try {
			List list = tripInfoLocalService.findTripsTypeInfoList();
			res.setCode(ResultCode.SUCCESS.get_code());
			res.setMsg("获取行程类型成功");
			res.setData(list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			res.setCode(ResultCode.UNSUCCESS.get_code());
			res.setMsg("获取行程类型失败");
			return JSON.toJSONString(res);
		}
		return JSON.toJSONString(res);
	}

	/**
	 * 添加行程
	 * 
	 * @Title: addTripInfo
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param request
	 * @return
	 * @return: String
	 * @author: LiTeng
	 * @throws @date:
	 *             2016年10月17日 上午9:46:15
	 */
	@RequestMapping("/addTripInfo")
	@ResponseBody
	public String addTripInfo(HttpServletRequest request) {
		ResultBean res = new ResultBean();
		try {
			// 接参
			TripInfo tripInfo = HttpUtils.initParam(request, TripInfo.class);
			if (null == tripInfo) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg(ResultCode.ParamException.getMsg());
				return JSON.toJSONString(res);
			}
			String userId = HttpUtils.getParam(request, "consume", "");
			if(!userId.equals(tripInfo.getUserId())){
				res.setCode(ResultCode.ParamException.get_code());
    			res.setMsg("用户身份验证失败");
    			return JSON.toJSONString(res);
			}
			if (tripInfo == null || StringUtils.isBlank(tripInfo.getUserId())) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("用户标示参数错误");
				return JSON.toJSONString(res);
			}
			if (tripInfo.getTime() == null) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程时间参数错误");
				return JSON.toJSONString(res);
			}
			if (StringUtils.isBlank(tripInfo.getTitle())) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程主题不能为空");
				return JSON.toJSONString(res);
			}
			if (StringUtils.isBlank(tripInfo.getContent())) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程内容不能为空");
				return JSON.toJSONString(res);
			}
			if (StringUtils.isBlank(tripInfo.getImgUrl())) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程图片不能为空");
				return JSON.toJSONString(res);
			}
			if ((tripInfo.getIsOpen() == null || (tripInfo.getIsOpen() != 1 && tripInfo.getIsOpen() != 2))) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程是否公开参数错误");
				return JSON.toJSONString(res);
			}
			if(tripInfo.getIsOpen() == 1 && tripInfo.getOpentime() == null){
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("公开的行程公开时间必填");
				return JSON.toJSONString(res);
			}
			if (StringUtils.isBlank(tripInfo.getTripCity())) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程城市不能为空");
				return JSON.toJSONString(res);
			}
			if (StringUtils.isBlank(tripInfo.getType()) || !this.isNumeric(tripInfo.getType())) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程类型参数错误");
				return JSON.toJSONString(res);
			}
			int typeNum = tripInfoLocalService.findTripsTypeCountById(tripInfo.getType());
			if (typeNum <= 0) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程类型选择错误");
				return JSON.toJSONString(res);
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			int num = tripInfoLocalService.findTripsCountByTime(tripInfo.getUserId().toString(),
					sdf.format(tripInfo.getTime()), "'%Y-%m-%d'", 0);
			if (num > 5) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("该行程日期已超出5个行程上线");
				return JSON.toJSONString(res);
			}
			int tnum = tripInfoLocalService.findTripsCountByTime(tripInfo.getUserId().toString(),
					sdf.format(tripInfo.getTime()), "'%Y-%m-%d %H:%i:%s'", 0);
			if (tnum > 0) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("该行程时间已存在行程");
				return JSON.toJSONString(res);
			}
			int ib = tripInfoLocalService.saveTripInfo(tripInfo);
			if (ib > 0) {
				res.setCode(ResultCode.SUCCESS.get_code());
			} else {
				res.setCode(ResultCode.UNSUCCESS.get_code());
				res.setMsg("添加失败");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			res.setCode(ResultCode.UNSUCCESS.get_code());
			res.setMsg("添加失败");
			return JSON.toJSONString(res);
		}
		return JSON.toJSONString(res);
	}

	/**
	 * 修改个人行程
	 * 
	 * @Title: updateTripInfo
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param request
	 * @return
	 * @return: String
	 * @author: LiTeng
	 * @throws @date:
	 *             2016年10月17日 上午9:55:09
	 */
	@RequestMapping("/updateTripInfoByid")
	@ResponseBody
	public String updateTripInfo(HttpServletRequest request) {
		ResultBean res = new ResultBean();
		try {
			// 接参
			TripInfo tripInfo = HttpUtils.initParam(request, TripInfo.class);
			if (null == tripInfo) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg(ResultCode.ParamException.getMsg());
				return JSON.toJSONString(res);
			}
			String userId = HttpUtils.getParam(request, "consume", "");
			if(!userId.equals(tripInfo.getUserId())){
				res.setCode(ResultCode.ParamException.get_code());
    			res.setMsg("用户身份验证失败");
    			return JSON.toJSONString(res);
			}
			if (tripInfo == null || StringUtils.isBlank(tripInfo.getUserId())) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("用户标示参数错误");
				return JSON.toJSONString(res);
			}
			if (tripInfo.getTime() == null) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程时间参数错误");
				return JSON.toJSONString(res);
			}
			if (StringUtils.isBlank(tripInfo.getTitle())) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程主题不能为空");
				return JSON.toJSONString(res);
			}
			if (StringUtils.isBlank(tripInfo.getContent())) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程内容不能为空");
				return JSON.toJSONString(res);
			}
			if (StringUtils.isBlank(tripInfo.getImgUrl())) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程图片不能为空");
				return JSON.toJSONString(res);
			}
			if ((tripInfo.getIsOpen() == null || (tripInfo.getIsOpen() != 1 && tripInfo.getIsOpen() != 2))) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程是否公开参数错误");
				return JSON.toJSONString(res);
			}
			if(tripInfo.getIsOpen() == 1 && tripInfo.getOpentime() == null){
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("公开的行程公开时间必填");
				return JSON.toJSONString(res);
			}
			if (StringUtils.isBlank(tripInfo.getTripCity())) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程城市不能为空");
				return JSON.toJSONString(res);
			}
			if (StringUtils.isBlank(tripInfo.getType()) || !this.isNumeric(tripInfo.getType())) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程类型参数错误");
				return JSON.toJSONString(res);
			}
			int typeNum = tripInfoLocalService.findTripsTypeCountById(tripInfo.getType());
			if (typeNum <= 0) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("行程类型选择错误");
				return JSON.toJSONString(res);
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			int num = tripInfoLocalService.findTripsCountByTime(tripInfo.getUserId().toString(),
					sdf.format(tripInfo.getTime()), "'%Y-%m-%d'", tripInfo.getId() == null ? 0 : tripInfo.getId());
			if (num > 5) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("该行程日期已超出5个行程上线");
				return JSON.toJSONString(res);
			}
			int tnum = tripInfoLocalService.findTripsCountByTime(tripInfo.getUserId().toString(),
					sdf.format(tripInfo.getTime()), "'%Y-%m-%d %H:%i:%s'",
					tripInfo.getId() == null ? 0 : tripInfo.getId());
			if (tnum > 0) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("该行程时间已存在行程");
				return JSON.toJSONString(res);
			}
			tripInfoLocalService.updateTripInfo(tripInfo);
			res.setCode(ResultCode.SUCCESS.get_code());
			res.setMsg("修改行程成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			res.setCode(ResultCode.UNSUCCESS.get_code());
			res.setMsg("添加失败");
			return JSON.toJSONString(res);
		}
		return JSON.toJSONString(res);
	}

	/**
	 * 删除个人行程
	 * @Title: deleteTripInfoByid   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param request
	 * @return      
	 * @return: String
	 * @author: LiTeng      
	 * @throws 
	 * @date:   2016年10月17日 上午10:04:33
	 */
	@RequestMapping("/deleteTripInfoByid")
	@ResponseBody
	public String deleteTripInfoByid(HttpServletRequest request) {
		ResultBean res = new ResultBean();
		try {
			// 接参
			Map paramMap = HttpUtils.initParam(request, Map.class);
			if (null == paramMap || paramMap.isEmpty()) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg(ResultCode.ParamException.getMsg());
				return JSON.toJSONString(res);
			}
			String userId = MapUtils.getStrValue(paramMap, "userId", "");
			if (StringUtils.isBlank(userId)) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("用户获取失败");
				return JSON.toJSONString(res);
			}
			long tripId = MapUtils.getLongValue(paramMap, "tripId", 0L);
			int du = tripInfoLocalService.deleteTripInfo(tripId);
			if (du > 0) {
				res.setCode(ResultCode.SUCCESS.get_code());
			} else {
				res.setCode(ResultCode.UNSUCCESS.get_code());
				res.setMsg("删除失败");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			res.setCode(ResultCode.UNSUCCESS.get_code());
			res.setMsg("删除失败");
			return JSON.toJSONString(res);
		}
		return JSON.toJSONString(res);
	}
	
	/**
	 * 获取行程列表(星空图)
	 * @Title: findTripsByUserId   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param: @param model
	 * @param: @param userId
	 * @param: @param isOpen 是否查询公开 1-查看所有 2-只查看公开 
	 * @param: @param tripTime  获取时间点(不包含此时间，yyyy-MM-dd HH:mm:ss  为空查询最近指定条数)
	 * @param: @param mpageSize 获取条数(默认20)
	 * @param: @param direction   0-获取过去  1-获取未来
	 * @param: @return      
	 * @return: ResultBean
	 * @author: LiTeng      
	 * @throws 
	 * @date:   2016年8月26日 下午5:25:45
	 */
	@RequestMapping("/findTripsByUserId")
	@ResponseBody
	public String findTripsStarByUserId(HttpServletRequest request) {
		ResultBean res = new ResultBean();
		List list = new ArrayList<>();
		int size = 20;
		try {
			// 接参
			Map paramMap = HttpUtils.initParam(request, Map.class);
			if (null == paramMap || paramMap.isEmpty()) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg(ResultCode.ParamException.getMsg());
				return JSON.toJSONString(res);
			}
			String userId = MapUtils.getStrValue(paramMap, "userId", "");
			if (StringUtils.isBlank(userId)) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("用户获取失败");
				return JSON.toJSONString(res);
			}
			String mpageSize = MapUtils.getStrValue(paramMap, "mpageSize", "");
			if(!StringUtils.isBlank(mpageSize) && this.isNumeric(mpageSize)){
				size = Integer.parseInt(mpageSize);
			}
			String tripTime = MapUtils.getStrValue(paramMap, "tripTime", "");
			String isOpen = MapUtils.getStrValue(paramMap, "isOpen", "");
			String direction = MapUtils.getStrValue(paramMap, "direction", "");
			if(StringUtils.isBlank(tripTime))
	        {
				Map map = tripInfoLocalService.findTripsInfoLately(userId, isOpen);
				if(map !=null){
					if(map.containsKey("time") && map.get("time")!=null && !StringUtils.isBlank(map.get("time").toString())){
						list = tripInfoLocalService.findTripsForInit(userId, isOpen, size,map.get("time").toString());
					}
				}
				
	        }else{
	        	if(StringUtils.isBlank(mpageSize) || (!direction.equals("1") && !direction.equals("0"))){
	        		res.setCode(ResultCode.ParamException.get_code());
					res.setMsg("请求方向出错");
					return JSON.toJSONString(res);
	        	}
	        	list = tripInfoLocalService.findTripsByTimeDirection(userId, isOpen,tripTime,size,direction);
	        }
			res.setCode(ResultCode.SUCCESS.get_code());
			res.setMsg(ResultCode.SUCCESS.getMsg());
			res.setData(list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			res.setCode(ResultCode.UNSUCCESS.get_code());
			res.setMsg("获取星空图失败");
			return JSON.toJSONString(res);
		}
		return JSON.toJSONString(res);
	}
	
	/**
	 * 获取行程最近一条
	 * @Title: findTripsInfoLately   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param: @param model
	 * @param: @param userId
	 * @param: @param isOpen
	 * @param: @param po
	 * @param: @return      
	 * @return: ResultBean
	 * @author: LiTeng      
	 * @throws 
	 * @date:   2016年8月31日 下午2:02:14
	 */
	@RequestMapping("/findTripsInfoLately")
	@ResponseBody
	public String findTripsInfoLately(HttpServletRequest request) {
		ResultBean res= new ResultBean();
        try {
			//接参
    		Map paramMap = HttpUtils.initParam(request, Map.class);
    		if (null == paramMap || paramMap.isEmpty()) {
    			res.setCode(ResultCode.ParamException.get_code());
    			res.setMsg(ResultCode.ParamException.getMsg());
    			return JSON.toJSONString(res);
    		}
    		String isOpen = MapUtils.getStrValue(paramMap, "isOpen", "");
			String userId = MapUtils.getStrValue(paramMap, "userId", "");
			if (StringUtils.isBlank(userId)) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("用户获取失败");
				return JSON.toJSONString(res);
			}
			Map map = tripInfoLocalService.findTripsInfoLately(userId,isOpen);
			res.setCode(ResultCode.SUCCESS.get_code());
			res.setData(map);
			return JSON.toJSONString(res,SerializerFeature.DisableCircularReferenceDetect);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			res.setCode(ResultCode.UNSUCCESS.get_code());
			return JSON.toJSONString(res,SerializerFeature.DisableCircularReferenceDetect);
		}
	}
	
	/**
	 * 分页获取行程列表（时间倒序）
	 * @Title: findTripsPage   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param request
	 * @return      
	 * @return: String
	 * @author: LiTeng      
	 * @throws 
	 * @date:   2016年10月17日 下午1:03:16
	 */
	@RequestMapping("/findTripsPage")
	@ResponseBody
	public String findTripsPage(HttpServletRequest request) {
		ResultBean res= new ResultBean();
		Page page = new Page();
        try {
			//接参
    		Map paramMap = HttpUtils.initParam(request, Map.class);
    		if (null == paramMap || paramMap.isEmpty()) {
    			res.setCode(ResultCode.ParamException.get_code());
    			res.setMsg(ResultCode.ParamException.getMsg());
    			return JSON.toJSONString(res);
    		}
    		String isOpen = MapUtils.getStrValue(paramMap, "isOpen", "");
			page.pageNo = MapUtils.getIntValue(paramMap,"pageNo",page.pageNo);
			page.pageSize = MapUtils.getIntValue(paramMap,"pageSize",page.pageSize);
			String userId = MapUtils.getStrValue(paramMap, "userId", "");
			if (StringUtils.isBlank(userId)) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("用户获取失败");
				return JSON.toJSONString(res);
			}
			page = tripInfoLocalService.findTripsPage(userId,isOpen,page);
			res.setCode(ResultCode.SUCCESS.get_code());
			res.setData(page);
			return JSON.toJSONString(res,SerializerFeature.DisableCircularReferenceDetect);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			res.setCode(ResultCode.UNSUCCESS.get_code());
			return JSON.toJSONString(res,SerializerFeature.DisableCircularReferenceDetect);
		}
	}
	/**
	 * 获取个人行程数据（星空图第一版用，之后作废）
	 * @Title: findTripsStarChart   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param userId
	 * @param isOpen
	 * @param time
	 * @return      
	 * @return: List
	 * @author: LiTeng      
	 * @throws 
	 * @date:   2016年10月26日 下午2:35:37
	 */
	@RequestMapping("/findTripsStarChart")
	@ResponseBody
	public String findTripsStarChart(HttpServletRequest request) {
		ResultBean res = new ResultBean();
		List list = new ArrayList<>();
		try {
			// 接参
			Map paramMap = HttpUtils.initParam(request, Map.class);
			if (null == paramMap || paramMap.isEmpty()) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg(ResultCode.ParamException.getMsg());
				return JSON.toJSONString(res);
			}
			String userId = MapUtils.getStrValue(paramMap, "userId", "");
			if (StringUtils.isBlank(userId)) {
				res.setCode(ResultCode.ParamException.get_code());
				res.setMsg("用户获取失败");
				return JSON.toJSONString(res);
			}
			String isOpen = MapUtils.getStrValue(paramMap, "isOpen", "");
			Map map = tripInfoLocalService.findTripsInfoLately(userId, isOpen);
			if(map !=null){
				if(map.containsKey("time") && map.get("time")!=null && !StringUtils.isBlank(map.get("time").toString())){
					list = tripInfoLocalService.findTripsStarChart(userId, isOpen, map.get("time").toString());
				}
			}
			res.setCode(ResultCode.SUCCESS.get_code());
			res.setMsg(ResultCode.SUCCESS.getMsg());
			res.setData(list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			res.setCode(ResultCode.UNSUCCESS.get_code());
			res.setMsg("获取星空图失败");
			return JSON.toJSONString(res);
		}
		return JSON.toJSONString(res);
	}

	public static boolean isNumeric(String src) {
		boolean return_value = false;
		if (src != null && src.length() > 0) {
			Matcher m = Pattern.compile("^[0-9\\-]+$").matcher(src);
			if (m.find()) {
				return_value = true;
			}
		}
		return return_value;
	}
}
